package cn.com.chengmandian.bike.controller;


import cn.com.chengmandian.bike.dto.MemberLocationForm;
import cn.com.chengmandian.bike.dto.StationNearDto;
import cn.com.chengmandian.bike.model.vo.RouteVo;
import cn.com.chengmandian.bike.model.vo.OperationStationVo;
import cn.com.chengmandian.bike.service.IEbOperationStationService;
import cn.com.chengmandian.core.common.utils.LnglatUtil;
import cn.com.chengmandian.core.web.pojo.AgentInfo;
import cn.com.chengmandian.core.web.pojo.AjaxResult;
import cn.com.chengmandian.core.web.pojo.amap.BicycleData;
import cn.com.chengmandian.core.web.pojo.amap.Path;
import cn.com.chengmandian.core.web.pojo.amap.Step;
import cn.com.chengmandian.core.web.service.AmapService;
import cn.com.chengmandian.core.web.service.TxMapService;
import cn.com.chengmandian.core.web.utils.LocalMapUtil;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.util.ArrayList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 * 运营站点配置 前端控制器
 * </p>
 *
 * @author AutoGenerator
 * @since 2021-12-09
 */
@Api(tags = "运营站点相关接口")
@RestController
@RequestMapping("/operation/station")
public class EbOperationStationController {
    @Autowired
    private IEbOperationStationService operationStationService;

    @Autowired
    private TxMapService txMapService;

    @Autowired
    private AmapService amapService;

    @ApiOperation("获取站点列表(无需登录)")
    @GetMapping("/list")
    public AjaxResult<List<OperationStationVo>> list() {
        AgentInfo agentInfo = LocalMapUtil.getAgentInfo();
        Assert.notNull(agentInfo.getAreaId(), "缺少运营区");
        return AjaxResult.success(operationStationService.getStationList(agentInfo.getAreaId()));
    }

    @ApiOperation("附近站点(无需登录)")
    @GetMapping("/near/list")
    public AjaxResult<List<OperationStationVo>> nearList(StationNearDto dto){
        AgentInfo agentInfo = LocalMapUtil.getAgentInfo();
        Assert.notNull(agentInfo.getAreaId(), "缺少运营区");
        Assert.notNull(dto.getLat(), "缺少维度");
        Assert.notNull(dto.getLng(), "缺少经度");
        return AjaxResult.success(operationStationService.getNearStationList(agentInfo.getAreaId(), dto.getLng(), dto.getLat()));
    }

    @ApiOperation("骑行找停车点路径规划(无需登录)")
    @PostMapping("/bicycling/{stationId}")
    public AjaxResult<List<RouteVo>> walking(@PathVariable("stationId") Integer stationId, @RequestBody MemberLocationForm memberLocationForm) {
        Assert.isTrue(stationId != null, "缺少停车点ID");
        OperationStationVo operationStationVo = operationStationService.getStation(stationId);
        Assert.notNull(operationStationVo, "不存在的停车点");
        BigDecimal[] center = LnglatUtil.getCenterOfPolygon(operationStationVo.getLngs().split(","), operationStationVo.getLats().split(","));
        BicycleData bicycleData = amapService.directionBicycling(memberLocationForm.getLng(),memberLocationForm.getLat(), center[0],center[1]);
        List<Path> paths = bicycleData.getPaths();
        List<RouteVo> routeList = new ArrayList<>();
        for (int i = 0; i < paths.size(); i++) {
            RouteVo routeVo = new RouteVo();
            Path path = paths.get(i);
            List<Step> stepList = path.getSteps();
            List<JSONObject> steps = new ArrayList<>();
            int idx = 0;
            String poly = "";
            int ll = 0;
            int len = 0;
            for (int j = 0; j < stepList.size(); j++) {
                Step step = stepList.get(j);
                String[] polyStrings = step.getPolyline().split(";");
                len = len + polyStrings.length * 2;
            }
            BigDecimal[] bigDecimals = new BigDecimal[len];
            for (int j = 0; j < stepList.size(); j++) {
                JSONObject stepJson = new JSONObject();
                Step step = stepList.get(j);
                String[] polyStrings = step.getPolyline().split(";");
                for (int k = 0; k < polyStrings.length; k++) {
                    String[] split = polyStrings[k].split(",");
                    poly = poly + split[1]+","+split[0]+";";
                    bigDecimals[ll] = new BigDecimal(split[1]);
                    bigDecimals[ll+1] = new BigDecimal(split[0]);
                    ll = ll + 2;
                }
                int l = (int) poly.chars().filter(c -> c == ',').count();
                int idxEnd = idx + l * 2 - 1;
                stepJson.put("mode", "BICYCLING");
                stepJson.put("instruction", step.getInstruction());
                stepJson.put("polyline_idx", new Integer[]{idx, idxEnd});
                stepJson.put("road_name", step.getRoad());
                stepJson.put("dir_desc", step.getOrientation());
                stepJson.put("distance", step.getDistance());
                stepJson.put("act_desc", step.getAction());
                stepJson.put("type", step.getWalk_type());
                steps.add(stepJson);
                idx = idxEnd + 1;
            }
            BigDecimal[] polyLine = new BigDecimal[bigDecimals.length];
            polyLine[0] = bigDecimals[0];
            polyLine[1] = bigDecimals[1];
            //前向差分压缩
            for (int t = 2; t < bigDecimals.length ; t++) {
                polyLine[t] = BigDecimal.valueOf(1000000).multiply(bigDecimals[t].subtract(bigDecimals[t-2]));
            }

            routeVo.setPolyline(polyLine);
            routeVo.setSteps(steps);
            routeVo.setDuration( Math.round((float) path.getDuration()/60));
            routeVo.setDistance(path.getDistance());

            routeList.add(routeVo);
        }
        return AjaxResult.success(routeList);
    }

    @ApiOperation("检查是否在站点")
    @PostMapping("/check/in")
    public AjaxResult<OperationStationVo> checkIn(@RequestBody MemberLocationForm memberLocationForm) {
        AgentInfo agentInfo = LocalMapUtil.getAgentInfo();
        Assert.notNull(agentInfo.getAreaId(), "缺少运营区");
        OperationStationVo res = operationStationService.checkIn(agentInfo.getAreaId(), memberLocationForm.getLng(), memberLocationForm.getLat());
        if (res == null) {
            return AjaxResult.error("不在站点");
        }
        return AjaxResult.success(res);
    }
}
